//
// Created by Administrator on 24-9-14.
//

#include "receiver.h"
#include <bitset>
#include  <iostream>

Receiver::Receiver(QObject* parent): QObject{parent}
{
    serialPort = new QSerialPort(this);
    connect(serialPort,&QSerialPort::readyRead, this, &Receiver::recieveData);
}

void Receiver::clearGR(int flag)
{
    if(flag==0)
    {
        plot->xAxisValue=0;
        for(int i=0;i<9;i++)
        {
            plot->graph(i)->data().data()->clear();
        }
    }else if(flag==1)
    {
        plot2->xAxisValue=0;
        for(int i=0;i<9;i++)
        {
            plot2->graph(i)->data().data()->clear();
        }
    }
}

void Receiver::parseToInt32(QByteArray byteArray)
{
    int plotIndex = 0;
    for (int i = 4; i < 58; i = i + 6)
    {
        QByteArray segment = byteArray.mid(i, 6);
        std::swap(segment[0], segment[4]);
        std::swap(segment[1], segment[5]);
        bool ok;
        double decimalValue;
        if(i==4)
        {
            // qDebug()<<"a:"<<segment;
            char isAbove = segment[0];
            segment[0]='0';
            decimalValue = isAbove=='0'?segment.toInt(&ok,16):-segment.toInt(&ok,16);
        }else
        {
            decimalValue = segment.toInt(&ok,16);
            decimalValue = decimalValue/aVector.at(plotIndex)+bVector.at(plotIndex);
        }
        if(ok)
        {
            if(i==4)
            {
                plot->graph(8)->addData(plot->xAxisValue,decimalValue);
                plot2->graph(8)->addData(plot2->xAxisValue,decimalValue);
                // if(abs(decimalValue-8000)>100)
                // {
                //     qDebug()<<decimalValue;
                // }
                continue;
            }
            plot->graph(plotIndex)->addData(plot->xAxisValue,decimalValue);
            plot2->graph(plotIndex)->addData(plot2->xAxisValue,decimalValue);
            plotIndex++;
        }else
        {
            qDebug()<<"转换失败";
        }
    }
    plot->xAxisValue++;
    plot2->xAxisValue++;
    if(plot->xAxisValue==10000)
    {
        // QScreen *screen = QGuiApplication::primaryScreen();
        // QDateTime currentDateTime = QDateTime::currentDateTime();
        // QString dateTimeString = currentDateTime.toString("yyyy-MM-dd-hh-mm-ss");
        // screen->grabWindow(0).save("./"+dateTimeString+".png", "png");
        // 获取应用程序的主窗口
        QWidget *mainWindow = QApplication::activeWindow();
        if (mainWindow != nullptr) {
            QScreen *screen = mainWindow->screen();
            QDateTime currentDateTime = QDateTime::currentDateTime();
            QString dateTimeString = currentDateTime.toString("yyyy-MM-dd-hh-mm-ss");
            QPixmap screenshot = screen->grabWindow(mainWindow->winId());
            if (!screenshot.isNull()) {
                screenshot.save(QString("./%1.png").arg(dateTimeString), "png");
            } else {
                qDebug() << "截图为空";
            }
        } else {
            qDebug() << "主窗口无效";
        }
        clearGR(0);
    }
    if(plot2->xAxisValue==1000)
    {
        clearGR(1);
    }
}
void Receiver::recieveData()
{
    QByteArray frame=serialPort->readAll();
    // qDebug()<<frame.toHex();
    if(frame.size()>0){
    serialData.append(frame.toHex());
    QByteArray frameHead = "55aa";
    int index = 0;
    while ((index = serialData.indexOf(frameHead)) != -1)
    {
        if (index + PER_READ >serialData.size())
            break;
        QByteArray dataToRemove = serialData.mid(index, PER_READ);
        if (dataToRemove.size() >= 3 && dataToRemove.right(2) != "f0")
        {
            QByteArray errorData=serialData.remove(0, index + frameHead.size());
            qDebug()<<errorData;
            continue;
        }
        serialData.remove(0, index + PER_READ);
        // qDebug()<<dataToRemove;
        parseToInt32(dataToRemove);
    }
    }else
    {
        qDebug()<<"NothingToRead";
    }
    if(serialData.size() > 1000)
    {
        qDebug()<<"缓存超过1000,请检查数据源或者匹配格式";
        serialData.clear();
    }
}

void Receiver::openS(QString s)
{
    serialPort->setPortName(s);
    serialPort->setBaudRate(115200);
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);
    // qDebug() << " 实际波特率为: " << serialPort->baudRate();
    // serialPort->setReadBufferSize(1073741824);  //设置内部读缓冲区的大小（如果不设置默认最大是4096字节）
    if (!(serialPort->open(QSerialPort::ReadWrite)))
    {
        qDebug() << "串口打开失败";
    }else
    {
        emit changePushButton(true);
    }
}

void Receiver::closeS()
{
    serialPort->flush();
    serialPort->clear();
    serialPort->close();
    emit changePushButton(false);
    serialData.clear();
}

void Receiver::changeAB(double a, double b,int index)
{
   aVector.at(index)=a;
   bVector.at(index)=b;
}
